<template>
  <div :class="['!w-[var(--left-tree-max-width)]  tree-min-width']">
    <div class="pl-12px mt-20px">
         <div class="flex-1 mb-15px f-s16 font-bold">采集任务/工程名称</div>
      <div class="flex items-center">
        <el-select
          v-model="currentTask"

          placeholder="请选择采集任务"
          @change="handleTaskChange"
          style="width: 240px"
        >
          <el-option
            v-for="item in taskOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :show-file-list="false"

          :on-change="(file) => handleFileChange(file, 'packet')"
        >
        <!--  :accept="'.xlsx,.xls'" -->
          <BaseButton class="opBtn mx-12px" size="" type="primary"
            >导入</BaseButton
          >
        </el-upload>
      </div>
      <el-select
        class="mt-15px"
        v-model="currentDepartment"

        placeholder="请选择工程名称"
        @change="handleProductChange"
      >
        <el-option
          v-for="item in departmentOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <!-- <el-cascader

     v-model="currentDepartment"
    :options="options"
     @change="handleProductChange"></el-cascader> -->
    </div>

    <ElDivider />
    <div class="items-center mt-20px pl-12px">
      <div class="flex-1 mb-15px f-s16 font-bold">型号设备树</div>
      <ElInput
        v-model="currentchlDepartment"
        class="flex-[2]"
        placeholder="搜索设备型号"
      />
    </div>
    <div class="h-[calc(100%-280px)] overflow-y pl-15px mt-15px">
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all

        :expand-on-click-node="false"
        node-key="deviceCode"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'deviceName',
          children: 'children',
          class: customNodeClass,
        }"
        :filter-node-method="filterNode"
        @current-change="handleCurrentChange"
      >
        <template #default="{ data }">
          <div
            :title="data.deviceName"
            class="whitespace-nowrap overflow-ellipsis overflow-hidden"
          >
            {{ data.deviceName }}
          </div>
        </template>
      </ElTree>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, defineProps, defineEmits, nextTick } from "vue";
import { ElTree, ElInput, ElDivider, ElMessage } from "element-plus";
import type { DepartmentItem } from "@/components/DepartmentTree/types";
import { useDeviceTreeStore } from "@/store/modules/deviceTreeStore";

// 使用Pinia store
const deviceTreeStore = useDeviceTreeStore();
const currentTask = ref(deviceTreeStore.currentTask);



// 定义Emits
const emit = defineEmits([
  "current-change",
  "department-change",
  "upload-packet",
  "task-change",
]);



const currentchlDepartment = ref("");
const departmentOptions = ref<{ label: string; value: string }[]>([]);
const currentDepartment = ref();
const currentNodeKey = ref();
const treeEl = ref<InstanceType<typeof ElTree>>();
const departmentList = ref<DepartmentItem[]>([]);
const taskOptions = ref<{ label: string; value: string }[]>([]);


// 添加标志位防止重复调用
const isTreeLoading = ref(false);
const isTaskChanging = ref(false);

// 修改自定义节点类，只对当前选中节点应用样式
const customNodeClass = (data: DepartmentItem, node: any) => {
  return node.isCurrent ? "is-current-node" : "";
};

const handleFileChange = (file: File, type: string) => {
  emit("upload-packet", file, type);
};

// 获取任务
const taskData = async () => {
  const res = await "/api/mission/list".post({});
  taskOptions.value = res.data.map((item) => ({
    label: item.name + ":【" + item.superiorExportTime.slice(0, 10) + "】",
    value: item.missionCode,
    data: item,
  }));

  if (taskOptions.value.length > 0) {
    const firstTaskValue = taskOptions.value[0].value;
    const firstTaskInfo = res.data.find(item => item.missionCode === firstTaskValue);
    currentTask.value = firstTaskValue;
    deviceTreeStore.setCurrentTask(firstTaskValue);
    deviceTreeStore.setTaskInfo(firstTaskInfo);

    emit("task-change", firstTaskInfo);
    // 直接获取树数据，不通过 getRootDepartment
    await getRootDepartment(firstTaskValue);
  }else {
    deviceTreeStore.setCurrentTask("");
     deviceTreeStore.setTaskInfo({});
  }
};

// 获取根节点
const getRootDepartment = async (id: string) => {
  try {
    const res = await "/dDeviceCatalog/rootList".get({
      missionCode: id,
    });
    departmentOptions.value = res.data.map((item) => ({
      label: item.deviceName,
      value: item.deviceCode,
    }));

    // 如果store中有保存的根节点，使用它，否则使用第一个选项
    if (
      deviceTreeStore.currentDepartment &&
      departmentOptions.value.some(
        (opt) => opt.value === deviceTreeStore.currentDepartment
      )
    ) {
      currentDepartment.value = deviceTreeStore.currentDepartment;
    } else if (departmentOptions.value.length > 0) {
      currentDepartment.value = departmentOptions.value[0].value;
      deviceTreeStore.setCurrentDepartment(currentDepartment.value);
    } else {
      currentDepartment.value = "";
    }

    // 只有在不是任务切换时才自动获取树数据
    if (currentDepartment.value && !isTaskChanging.value) {
      await getTree(currentDepartment.value, 0);
    }
  } catch (error) {
    console.error("获取根节点失败:", error);
  }
};

// 获取树
const getTree = async (rootCode: string, level: number) => {
  // 防止重复调用
  if (isTreeLoading.value) {
    return;
  }



  isTreeLoading.value = true;
  try {
    const res = await "/dDeviceCatalog/tree".get({
      parentCode: rootCode,
      missionCode: currentTask.value,
    });
     const treeData = [res.data] || [];
    departmentList.value = treeData;

    // 关键：将设备树数据设置到 Store 中
    deviceTreeStore.setDepartmentList(treeData);

    await nextTick();

    // 总是选中第一个节点
    selectFirstNode();
  } catch (error) {
    console.error("获取树数据失败:", error);
    departmentList.value = [];
    deviceTreeStore.setDepartmentList([]);
  } finally {
    isTreeLoading.value = false;
  }
};

// 选中第一个节点
const selectFirstNode = () => {
  if (departmentList.value.length > 0) {
    const firstNode = findFirstNode(departmentList.value[0]);
    if (firstNode) {
      currentNodeKey.value = firstNode.deviceCode;
      treeEl.value?.setCurrentKey(firstNode.deviceCode);

      // 确保触发 current-change 事件
      setTimeout(() => {
        handleCurrentChange(firstNode);
      }, 100);
    }
  }
};

// 辅助函数：查找树中的第一个节点
const findFirstNode = (node: DepartmentItem): DepartmentItem => {
  if (!node) return null;
  return node;
};

// 选择任务 - 修改后的版本
const handleTaskChange = async (value: string) => {
  if (!value) return;

  isTaskChanging.value = true;

  deviceTreeStore.setCurrentTask(value);

  const selectedTaskInfo = taskOptions.value.find((item) => item.value === value)?.data;
  if (selectedTaskInfo) {
    deviceTreeStore.setTaskInfo(selectedTaskInfo);
    emit("task-change", selectedTaskInfo);
  }
currentchlDepartment.value = "";
  // 获取新的根节点列表
  await getRootDepartment(value);

  // 任务切换后，自动选中第一个根节点和第一个设备
  if (departmentOptions.value.length > 0) {
    const firstRootValue = departmentOptions.value[0].value;
    currentDepartment.value = firstRootValue;
    deviceTreeStore.setCurrentDepartment(firstRootValue);

    // 直接获取树数据
    await getTree(firstRootValue, 1);

    emit("department-change", firstRootValue);
  }

  isTaskChanging.value = false;
};

// 产品切换 - 修改后的版本
const handleProductChange = async (value: string) => {
  if (!value) return;

  currentDepartment.value = value;
  deviceTreeStore.setCurrentDepartment(value);
currentchlDepartment.value = "";
  await getTree(value, 1);

  // 确保选中第一个节点并触发事件
  if (departmentList.value.length > 0) {
    const firstNode = findFirstNode(departmentList.value[0]);
    if (firstNode) {
      currentNodeKey.value = firstNode.deviceCode;
      treeEl.value?.setCurrentKey(firstNode.deviceCode);
      handleCurrentChange(firstNode);
    }
  }

  emit("department-change", value);
};

const filterNode = (value: string, data: DepartmentItem) => {
  if (!value) return true;
  return data.deviceName.includes(value);
};


// 当前节点变化
const handleCurrentChange = (data: DepartmentItem) => {

  if (data) {
    // 保存到store
    deviceTreeStore.setCurrentNode(data);
    currentNodeKey.value = data.deviceCode;

    // 触发事件
    emit("current-change", data);
  }
};

// 监听搜索关键词变化
watch(
  () => currentchlDepartment.value,
  (val) => {
    treeEl.value!.filter(val);
  }
);

// 暴露方法供父组件调用
defineExpose({
  refreshTree: () => {
    if (currentDepartment.value) {
      getTree(currentDepartment.value, 0);
    }
  },
  refreshRootTree: () => {
    taskData();
  },
  setCurrentKey: (key: string) => treeEl.value?.setCurrentKey(key),
  getTreeData: () => departmentList.value,
});

onMounted(() => {
  taskData();
});
</script>

<style scoped lang="less">
.tree-min-width {
  min-width: 200px !important;
}

:deep(.el-tree-node__content) {
  height: 40px !important;
}

:deep(.is-current-node .el-tree-node .el-tree-node__content) {
  background-color: transparent !important;
  color: inherit !important;
  font-weight: normal;
}
:deep(.is-current-node > .el-tree-node__content) {
  background-color: var(--el-color-primary) !important;
  border-radius: 0 20px 20px 0;
  color: var(--el-tree-content-color) !important;
  font-weight: bold;
}

:deep(.el-tree) {
  background: transparent !important;
}

:deep(.el-card) {
  --el-card-bg-color: transparent !important;
  background-color: transparent !important;
}
</style>
